package servlet;

import dao.UserDao;
import dao.UserDaoImpl;
import pojo.User;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/login",name = "login",initParams = {
        @WebInitParam(name="encoding",value = "utf-8")
})
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username+" "+password);
        User user = null;
        try {
            user = userService.selectByUsername(username);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (user.getUsername().equals(username)&&user.getPassword().equals(password)){
            HttpSession session = req.getSession();
            session.setAttribute("username",user.getUsername());
//            session.setMaxInactiveInterval(30);//单位秒，session失效时间
            resp.sendRedirect("/success.jsp");
        }else {
            req.getRequestDispatcher("/fail.jsp").forward(req,resp);
        }
    }
}
